// 默认配置
const DEFAULT_SETTINGS = {
  savedSites: "",
  timeRange: "all_time",
  clearHistory: true,
  clearCookies: false,
  clearCache: false,
};

// 加载保存的配置
chrome.storage.sync.get(Object.keys(DEFAULT_SETTINGS), (data) => {
  const settings = { ...DEFAULT_SETTINGS, ...data };
  document.getElementById("siteUrls").value = settings.savedSites;
  document.getElementById("timeRange").value = settings.timeRange;
  document.getElementById("clearHistory").checked = settings.clearHistory;
  document.getElementById("clearCookies").checked = settings.clearCookies;
  document.getElementById("clearCache").checked = settings.clearCache;
});

document.getElementById("clearBtn").addEventListener("click", async () => {
  const siteUrlsInput = document.getElementById("siteUrls").value.trim();
  if (!siteUrlsInput) {
    updateStatus("请输入网址！", "error");
    return;
  }

  // 获取当前选项
  const settings = {
    savedSites: siteUrlsInput,
    timeRange: document.getElementById("timeRange").value,
    clearHistory: document.getElementById("clearHistory").checked,
    clearCookies: document.getElementById("clearCookies").checked,
    clearCache: document.getElementById("clearCache").checked,
  };

  // 保存配置
  chrome.storage.sync.set(settings);

  // 解析输入的网址（兼容不带协议的输入）
  const sites = siteUrlsInput
    .split(/[\n,]+/)
    .map(s => s.trim())
    .filter(s => s)
    .map(site => {
      if (!site.startsWith("http")) return `https://${site}`;
      return site;
    })
    .map(url => {
      try {
        const parsed = new URL(url);
        const hostname = parsed.hostname;
        // 生成多个匹配模式：完整域名、去掉www的域名、以及顶级域名
        const patterns = [hostname];
        
        // 如果包含www，也添加不带www的版本
        if (hostname.startsWith('www.')) {
          patterns.push(hostname.substring(4));
        } else {
          // 如果不包含www，也添加带www的版本
          patterns.push('www.' + hostname);
        }
        
        // 也匹配顶级域名
        const parts = hostname.split('.');
        if (parts.length >= 2) {
          const topDomain = parts.slice(-2).join('.');
          if (!patterns.includes(topDomain)) {
            patterns.push(topDomain);
          }
        }
        
        return {
          origin: parsed.origin,
          hostname: hostname,
          patterns: patterns,
          displayUrl: url
        };
      } catch (e) {
        return null;
      }
    })
    .filter(s => s);

  // 计算时间范围
  let since = 0;
  const now = Date.now();
  switch (settings.timeRange) {
    case "last_hour": since = now - 3600000; break;
    case "last_day": since = now - 86400000; break;
    case "last_week": since = now - 604800000; break;
  }

  try {
    const results = [];
    
    // 清除历史记录（使用chrome.history API手动删除，因为removeHistory不支持origin过滤）
    if (settings.clearHistory) {
      let totalDeletedCount = 0;
      
      // 获取所有历史记录
      const historyItems = await chrome.history.search({
        text: '',
        startTime: since,
        maxResults: 1000000
      });
      
      for (const site of sites) {
        let siteDeletedCount = 0;
        
        for (const historyItem of historyItems) {
          if (historyItem.url) {
            try {
              const itemUrl = new URL(historyItem.url);
              const itemHostname = itemUrl.hostname;
              
              // 检查是否匹配任何模式
              const matches = site.patterns.some(pattern => 
                itemHostname === pattern || itemHostname.endsWith('.' + pattern)
              );
              
              if (matches) {
                await chrome.history.deleteUrl({ url: historyItem.url });
                siteDeletedCount++;
                totalDeletedCount++;
              }
            } catch (urlError) {
              // 忽略无效的URL
            }
          }
        }
        
        if (siteDeletedCount > 0) {
          console.log(`已删除 ${site.hostname} 的 ${siteDeletedCount} 条历史记录`);
        }
      }
      
      results.push(`历史记录（${totalDeletedCount}条记录）`);
    }

    // 清除Cookies（支持按域名）
    if (settings.clearCookies) {
      const origins = sites.map(site => site.origin);
      await chrome.browsingData.removeCookies({ 
        since, 
        origins: origins 
      });
      results.push(`Cookies（${sites.length}个网站）`);
    }

    // 清除缓存（不支持按域名，需全局清除）
    if (settings.clearCache) {
      await chrome.browsingData.removeCache({ since });
      results.push("缓存（全局清除）");
    }

    updateStatus(
      `已清除：${results.join("、")}`,
      "success"
    );
  } catch (error) {
    updateStatus("清除失败：" + error.message, "error");
  }
});

// 辅助函数：生成清除的类型提示
function getSelectedTypes(settings) {
  const types = [];
  if (settings.clearHistory) types.push("历史记录");
  if (settings.clearCookies) types.push("Cookies");
  if (settings.clearCache) types.push("缓存");
  return types.join("、") || "无数据";
}

function updateStatus(message, type) {
  const statusEl = document.getElementById("status");
  statusEl.textContent = message;
  statusEl.style.color = 
    type === "error" ? "#dc3545" : 
    type === "warning" ? "#ffc107" : "#28a745";
}
